<template>
    
    
    <Popup ref="popupRef"
           :title="popupTitle"
           :async="true"
           width="550px"
           @close="handleClose"
           @confirm="handleSubmit"
    >
        
        <template v-slot:default>
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
                <el-form-item label="账号" prop="username">
                    <el-input
                        v-model="formData.username"
                        :disabled="isRoot"
                        placeholder="请输入账号"/>
                
                
                </el-form-item>
                
                
                <el-form-item label="头像">
                    <div>
                        <div>
                            <MaterialPicker v-model="formData.avatar" :limit="1"/>
                        </div>
                        <div class="form-tips">建议尺寸：100*100px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>
                
                
                <el-form-item label="名称" prop="nickname">
                    <el-input v-model="formData.nickname"
                              placeholder="请输入名称"
                              clearable/>
                </el-form-item>
                
                
                <el-form-item label="归属部门" prop="deptIds">
                    <el-tree-select
                        class="flex-1"
                        v-model="formData.deptIds"
                        :data="optionsData.dept"
                        clearable
                        node-key="id"
                        multiple
                        
                        :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return !!data.isStop
                            }
                        }"
                        
                        check-strictly
                        :default-expand-all="true"
                        placeholder="请选择上级部门"
                    />
                </el-form-item>
                
                <el-form-item label="岗位" prop="postIds">
                    <el-select
                        class="flex-1"
                        clearable
                        multiple
                        v-model="formData.postIds"
                        placeholder="请选择岗位"
                    >
                        <el-option
                            v-for="(item, index) in optionsData.post"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                
                
                <el-form-item label="角色" prop="roleIds">
                    <el-select
                        v-model="formData.roleIds"
                        :disabled="isRoot"
                        multiple
                        class="flex-1"
                        clearable
                        placeholder="请选择角色"
                    >
                        <el-option v-if="isRoot" label="系统管理员" value="0"/>
                        <el-option
                            v-for="(item, index) in optionsData.role"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                
                
                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model.trim="formData.password"
                        show-password
                        clearable
                        placeholder="请输入密码"
                    />
                </el-form-item>
                
                <el-form-item label="确认密码" prop="passwordConfirm">
                    <el-input
                        v-model.trim="formData.passwordConfirm"
                        show-password
                        clearable
                        placeholder="请输入确认密码"
                    />
                </el-form-item>
                
                
                <el-form-item label="管理员状态" v-if="!isRoot">
                    <el-switch v-model="formData.isDisable"
                               :active-value="0"
                               :inactive-value="1"/>
                
                </el-form-item>
                
                <el-form-item label="多处登录">
                    <div>
                        <el-switch
                            v-model="formData.isMultipoint"
                            :active-value="1"
                            :inactive-value="0"
                        />
                        <div class="text-tx-secondary text-xs leading-6 mt-1">允许多人同时在线登录</div>
                    
                    </div>
                
                </el-form-item>
            </el-form>
        </template>
    
    </Popup>


</template>

<script setup lang="ts">
import {defineExpose} from "@vue/runtime-core";
import {FormInstance} from "element-plus";
import feedback from "@/utils/feedback";
import Popup from '@/components/popup/index.vue'
import {UnwrapNestedRefs} from "@vue/reactivity";
import BeachRequestManager from "@/manager/base/BeachRequestManager";
import {getDepartmentList} from "@/api/system/SystemAuthDeptController";
import {adminAdd, adminDetail, adminEdit} from "@/api/system/SystemAuthAdminController";
import {postAll} from "@/api/system/SystemAuthPostController";
import {roleAll} from "@/api/system/SystemAuthRoleController";

const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()


// 定义表单数据
const formData = reactive({
    id: 0,
    username: '',
    nickname: '',
    deptIds: [],
    postIds: [],
    roleIds: [],
    avatar: '',
    password: '',
    passwordConfirm: '',
    isDisable: 0,
    isMultipoint: 1
})


// 定义表单数据验证规则
const formRules = {
    username: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    nickname: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    roleIds: [
        {
            type: 'array',
            required: true,
            message: '请选择角色',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ],
    passwordConfirm: [
        {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
}

// 标题属性
const title = ref('add')


// 定义事件
const emit = defineEmits(['success', 'close'])


const optionsData: UnwrapNestedRefs<any> = BeachRequestManager.useBeachRequest({
    role: {
        api: roleAll
    },
    post: {
        api: postAll
    },
    dept: {
        api: getDepartmentList
    }
})


/**
 * 定义密码错误抛出
 */
function passwordConfirmValidator(rule: object, value: string, callback: any) {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

/**
 *
 * type 什么类型打开控件
 *
 * @param type
 */
function open(type: string) {
    title.value = type
    popupRef.value?.open(type)
}


function handleClose() {
    emit('close')
}


async function handleSubmit() {
    await formRef.value?.validate()
    title.value == 'edit' ? await adminEdit(formData) : await adminAdd(formData)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
    
    
}


let popupTitle = computed(() => {
    return title.value == 'edit' ? '编辑管理员' : '新增管理员'
});


/**
 * 判断是否是root
 */
const isRoot = computed(() => {
    return formData.id === 1
})


/**
 * from 表单赋值
 *
 * @param row
 */
async function setFormData(row: any) {
    formRules.password = []
    formRules.passwordConfirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    
    const data = await adminDetail({id: row.id})
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}


defineExpose({
    open,
    setFormData
})


</script>


